/*
 * Copyright 2008-2009 Sanjay Dwivedi.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.isdinvestments.common.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

public class JpaDao<T extends Object> extends AbstractDao<T> implements Dao<T> {
	@PersistenceContext
	private EntityManager entityManager;
	
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	public void persist(T t) {
		entityManager.persist(t);
	}
	
	@SuppressWarnings("unchecked")
	public T get(Long id) {
		return (T) entityManager.find(getDomainClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public T getReference(Long id) {
		return (T) entityManager.getReference(getDomainClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getList() {
		Query q = entityManager.createQuery("from " + getDomainClassName());
		return q.getResultList();
	}
	
	public void update(T t) {
		entityManager.merge(t);
	}
	
	public void delete(T t) {
		entityManager.remove(t);
	}
	
	public void deleteById(Long id) {
		entityManager.remove(getReference(id));
	}
	
	public void deleteAll() {
		Query q = entityManager.createQuery("delete " + getDomainClassName());
		q.executeUpdate();
	}
	
	public long count() {
		Query q = entityManager
			.createQuery("select count(*) from " + getDomainClassName());
		return (Long) q.getSingleResult();
	}
}
